import React, { useState } from 'react';
import {
  Box,
  CardBase,
  IconButton,
  ListButton,
  Pill,
  SecondaryButton,
  Text,
  ThemeColorType,
  Tooltip,
} from '@nova-hf/ui';
import { IconType } from '@nova-hf/ui/umd/ts/src/icon-library/iconMap';
import { MainColorType } from '@nova-hf/ui/umd/ts/src/styles/vars.css';
import Authentication from 'beta/store/authentication';
import { formatDate, formatPrice } from 'beta/utils/helpers';
import { useTranslation } from 'beta/utils/i18n';
import { inject, observer } from 'mobx-react';
import { useRouter } from 'next/router';
import { useContractQuery, useDeactivateContractItemMutation } from 'typings/graphql';

import { SectionHeader } from '../../../thjonustur/[serviceId]/comoponents/SectionHeader';

type StatusInfo = {
  color: ThemeColorType;
  icon: IconType;
  text: string;
};

type ContractItemsContainerProps = {
  authentication?: Authentication;
};

const ContractItemsContainer = ({ authentication }: ContractItemsContainerProps) => {
  const { t } = useTranslation('containers');
  const router = useRouter();
  const isStaff = authentication?.isStaff;
  const contractId = typeof router?.query?.contractId === 'string' ? router?.query?.contractId : '';
  const [showContractItems, setShowContractItems] = useState(true);

  const { data, loading, error, refetch } = useContractQuery({
    variables: {
      input: {
        id: contractId.toString(),
        show_inactive_contract_items: true,
      },
    },
  });

  const [deactivateItem, { loading: loadingDeactivation }] = useDeactivateContractItemMutation();

  const contract = data?.contract;

  const contractItems = contract?.contractItems;

  const returnRouter = async (id: string) => {
    if (contract?.id && id) {
      await deactivateItem({
        variables: {
          input: {
            contractItemId: id,
            id: contract?.id,
          },
        },
        onCompleted: () => {
          refetch();
        },
      });
    }
  };

  const getType = (type?: string) => {
    switch (type) {
      case 'Service':
        return t('contractItemsContainer.types.service');
      case 'Device':
        return t('contractItemsContainer.types.device');
      case 'Signup':
        return t('contractItemsContainer.types.signup');
      default:
        return t('contractItemsContainer.types.unknown');
    }
  };

  const getStatusInfo = (status: string): StatusInfo | undefined => {
    if (status === 'Active') {
      return { color: 'success', icon: 'checkMark', text: t('contractItemsContainer.active') };
    }
    if (status === 'Inactive') {
      return { color: 'warning', icon: 'close', text: t('contractItemsContainer.inactive') };
    }
    if (status === 'Pending') {
      return { color: 'yellow', icon: 'return', text: t('contractItemsContainer.pending') };
    }

    return undefined;
  };

  if (!data || error || loading || !contractItems?.length) {
    return null;
  }

  return (
    <Box>
      <Box display="flex" flexDirection="column" gap={2}>
        <Box>
          <SectionHeader
            headerTitle={t('contractItemsContainer.contractItems')}
            rightActionNode={
              <SecondaryButton
                colorScheme={'purple'}
                icon={showContractItems ? 'minus' : 'add'}
                text={
                  showContractItems
                    ? t('contractItemsContainer.hide')
                    : t('contractItemsContainer.show')
                }
                onClick={() => setShowContractItems(!showContractItems)}
              />
            }
          />
        </Box>
        {showContractItems && (
          <Box>
            <Box borderBottomStyle="solid" color="black100" borderWidth="2px" paddingBottom={2}>
              <Box display="grid" gridTemplateColumns={7} gap={2} alignItems="center">
                <Text variant="eyebrowSmall">{t('contractItemsContainer.headers.name')}</Text>
                <Text variant="eyebrowSmall">{t('contractItemsContainer.headers.type')}</Text>
                <Text variant="eyebrowSmall">{t('contractItemsContainer.headers.price')}</Text>
                <Text variant="eyebrowSmall">{t('contractItemsContainer.headers.status')}</Text>
                <Text variant="eyebrowSmall">{t('contractItemsContainer.headers.created')}</Text>
                <Text variant="eyebrowSmall">{t('contractItemsContainer.headers.updated')}</Text>
                {isStaff && (
                  <Text variant="eyebrowSmall">{t('contractItemsContainer.headers.extra')}</Text>
                )}
              </Box>
            </Box>
            {contractItems?.map((item) => (
              <React.Fragment key={item?.id}>
                <Box display="grid" gridTemplateColumns={7} gap={2} alignItems="center" marginY={2}>
                  <Text variant="pSmallRegular">
                    {item?.variant?.name}
                    {}
                  </Text>
                  <Text variant="pSmallRegular">{getType(item?.type ?? '')}</Text>
                  <Text variant="pSmallRegular">
                    {formatPrice(item?.variant?.monthlyCharge ?? 0)}
                  </Text>
                  <Pill
                    text={getStatusInfo(item?.status ?? '')?.text ?? ''}
                    color={getStatusInfo(item?.status ?? '')?.color as MainColorType}
                    maxWidth="fitContent"
                    icon={{
                      icon: getStatusInfo(item?.status ?? '')?.icon,
                      color: item?.status === 'Pending' ? 'black100' : 'white',
                      size: 16,
                    }}
                  />
                  <Text variant="pSmallRegular">
                    {item?.created
                      ? formatDate(item?.created, 'dd.MM.yyyy')
                      : t('contractRequestsContainer.notFound')}
                  </Text>
                  <Text variant="pSmallRegular">
                    {item?.updated
                      ? formatDate(item?.updated, 'dd.MM.yyyy')
                      : t('contractRequestsContainer.notFound')}
                  </Text>
                  {item?.__typename === 'DeviceContractItem' && isStaff && (
                    <>
                      {item.rentalInfo?.trackingCode === 'NovaRouter' ? (
                        <IconButton
                          color="black100"
                          isLoading={loadingDeactivation}
                          icon="trash"
                          hiddenButtonText="Action button"
                          onClick={() => returnRouter(item.id)}
                        />
                      ) : (
                        <Tooltip shouldShowOnHover={false}>
                          <CardBase borderColor="grey200" dottedShadow="none" hasBorder>
                            <Box padding={2}>
                              <Text marginBottom={1} variant="pMediumBold">
                                {item?.trackingCode}
                              </Text>
                            </Box>
                          </CardBase>
                        </Tooltip>
                      )}
                    </>
                  )}
                  {item?.__typename === 'ServiceContractItem' && isStaff && (
                    <ListButton
                      icon="plus"
                      text={t('contractItemsContainer.lookAtService')}
                      href={`/beta/${item?.serviceInfo.userId}/thjonustur/${item.serviceId}`}
                      renderAs="a"
                    />
                  )}
                </Box>
                <Box
                  borderColor="grey200"
                  borderBottomStyle="solid"
                  borderWidth="1px"
                  marginBottom={2}
                ></Box>
              </React.Fragment>
            ))}
          </Box>
        )}
      </Box>
    </Box>
  );
};

export default inject('ui', 'authentication')(observer(ContractItemsContainer));
